package com.bruceliu.controller;

import com.bruceliu.bean.Food;
import com.bruceliu.bean.FoodType;
import com.bruceliu.service.FoodService;
import com.bruceliu.service.FoodTypeService;
import com.bruceliu.utils.PageUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @BelongsProject: RestaurantSystem
 * @BelongsPackage: com.bruceliu.controller
 * @Author: bruceliu
 * @QQ:1241488705
 * @CreateTime: 2020-02-29 22:50
 * @Description: TODO
 */
@Controller
@Scope("prototype")
public class FoodController {

    @Resource
    FoodService foodService;

    @Resource
    FoodTypeService foodTypeService;

    @RequestMapping("/food_queryList/{pageIndex}/{pageSize}")
    public String queryList(@PathVariable("pageIndex") int pageIndex, @PathVariable("pageSize") int pageSize, Food food, Model model) {
        System.out.println("当前页码:" + pageIndex);
        System.out.println("页面大小:" + pageSize);
        System.out.println("查询参数:" + food);
        int totalCount = foodService.totalCount(food);
        System.out.println("条数是:" + totalCount);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageStart", (pageIndex - 1) * pageSize);
        map.put("pageSize", pageSize);
        map.put("title", food.getTitle());
        List<Food> foods = foodService.getFoods(map);
        System.out.println("每页数据:" + foods);
        PageUtils<Food> pageUtils = new PageUtils<Food>(pageSize, pageIndex, totalCount, foods);
        model.addAttribute("pageUtils", pageUtils);
        model.addAttribute("food", food);
        return "foodList";
    }

    /**
     * @return 查询所有的菜系
     */
    @ResponseBody
    @RequestMapping("/food_findFoodTypes")
    public List<FoodType> findFoodTypes() {
        return foodTypeService.getAllFoodTypes();
    }

    /**
     * 新增带文件上传
     *
     * @param food
     */
    @RequestMapping("/food_add")
    public void addFood(Food food, @RequestParam("imageUrl") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        System.out.println("新增的参数:" + food);
        if (file.isEmpty()) {
            response.getWriter().write("<script>alert('菜品图片不能为空!');location.href='/page_saveFood';</script>");
            return;
        }
        //文件名
        String fileName = file.getOriginalFilename();
        //后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //大小（单位是字节，可以加入判断）
        int size = (int) file.getSize();
        System.out.println("后缀名：" + suffixName);
        System.out.println("文件名：" + fileName);
        System.out.println("文件大小：" + size);
        //最后保存的文件名
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("最后保存的文件名称：" + fileName);

        //获取跟目录
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        System.out.println("path:" + path.getAbsolutePath());
        //如果上传目录为/static/images/upload/，则可以如下获取：
        File upload = new File(path.getAbsolutePath(), "/public/upload");

        //获取真实的服务器路径
        File f = new File(upload.getAbsolutePath(), fileName);
        //检测是否存在该目录
        if (!f.getParentFile().exists()) {
            //不存在则创建当前目录
            f.getParentFile().mkdirs();
        }
        file.transferTo(f);
        System.out.println("文件上传成功,路径是:" + f.getAbsolutePath());

        food.setPhoto(fileName);
        int count = foodService.addFood(food);
        if (count > 0) {
            response.getWriter().write("<script>alert('菜品新增成功!');location.href='/food_queryList/1/5';</script>");
        } else {
            response.getWriter().write("<script>alert('菜品新增失败!');location.href='/page_saveFood';</script>");
        }
    }

    @RequestMapping("/food_toupdate/{id}")
    public String toupdate(@PathVariable("id") int id, Model model) {
        Food food = foodService.getById(id);
        model.addAttribute("food", food);
        return "updateFood";
    }

    @RequestMapping("/food_update")
    public void update(Food food, @RequestParam("imageUrl") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        System.out.println("新增的参数:" + food);
        if (!file.isEmpty()) {
            //文件名
            String fileName = file.getOriginalFilename();
            //后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //大小（单位是字节，可以加入判断）
            int size = (int) file.getSize();
            System.out.println("后缀名：" + suffixName);
            System.out.println("文件名：" + fileName);
            System.out.println("文件大小：" + size);
            //最后保存的文件名
            fileName = UUID.randomUUID() + suffixName;
            System.out.println("最后保存的文件名称：" + fileName);

            //获取跟目录
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            System.out.println("path:" + path.getAbsolutePath());
            //如果上传目录为/static/images/upload/，则可以如下获取：
            File upload = new File(path.getAbsolutePath(), "/public/upload");

            //获取真实的服务器路径
            File f = new File(upload.getAbsolutePath(), fileName);
            //检测是否存在该目录
            if (!f.getParentFile().exists()) {
                //不存在则创建当前目录
                f.getParentFile().mkdirs();
            }
            file.transferTo(f);
            System.out.println("文件上传成功,路径是:" + f.getAbsolutePath());
            food.setPhoto(fileName);//设置新的图片名
        }
        int count = foodService.updateFood(food);
        if (count > 0) {
            response.getWriter().write("<script>alert('菜品更新成功!');location.href='/food_queryList/1/5';</script>");
        } else {
            response.getWriter().write("<script>alert('菜品更新失败!');location.href='/food_toupdate/"+food.getId()+"';</script>");
        }
    }

    @RequestMapping("/food_delete/{id}")
    public void delete(@PathVariable("id") int id, HttpServletResponse response) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        int count = foodService.deleteFood(id);
        if (count > 0) {
            response.getWriter().write("<script>alert('菜品删除成功!');location.href='/food_queryList/1/5';</script>");
        } else {
            response.getWriter().write("<script>alert('菜品删除失败!');location.href='/food_queryList/1/5';</script>");
        }
    }

}
